package com.shujia.spark.core

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD

object Demo9GroupByOnGroupByKey {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("groupByKey")
    val sc = new SparkContext(conf)

    val linesRDD: RDD[String] = sc.textFile("data/students.txt")

    //转换成kv结构
    val kvRDD: RDD[(String, Int)] = linesRDD.map(line => {
      val clazz: String = line.split(",").last
      (clazz, 1)
    })

    /**
     * groupBy和groupByKey区别，
     * groupBy： shuffle过程中需要传输的数据量比groupByKey要多一点，效率低一点
     *
     * 大数据计算shuffle最耗时间
     * 1、shuffle需要将数据落地
     * 2、shuffle需要再网络中传输数据
     */
    val groupByRDD: RDD[(String, Iterable[(String, Int)])] = kvRDD
      .groupBy(kv => kv._1)

    groupByRDD.foreach(println)

    val groupByKeyRDD: RDD[(String, Iterable[Int])] = kvRDD.groupByKey()

    groupByKeyRDD.foreach(println)

    while (true) {}

  }
}
